package com.beiing.tianshuai.tianshuai.mine.ui;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.LoginBean;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.MD5Utils;
import com.beiing.tianshuai.tianshuai.util.RegexUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class SignUpEnterPasswordActivity extends BaseActivity {

    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.btn_submit)
    TextView mBtnSubmit;
    @BindView(R.id.tv_password_note)
    TextView mTvNote;

    /**
     * 当前注册的手机号码
     */
    private String mPhoneNum;

    /**
     * 当前获取到的验证码
     */
    private String mSafeCode;

    /**
     * 登录网络重连次数
     */
    private int retryConnectLogin;

    /**
     * 点击按钮时获取到的密码
     */
    private String mPassWord;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sign_up_enter_password;
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        mPhoneNum = intent.getStringExtra("phoneNum");
        mSafeCode = intent.getStringExtra("safeCode");
        initToolbar();
        initListener();
    }

    private void initToolbar() {
        mToolbarIvBack.setVisibility(View.VISIBLE);
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mToolbarTvTitle.setText("输入密码");
    }

    private void initListener() {
        /**
         * 检测密码输入格式
         */
        mEtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String mPassWord = editable.toString();
                if (mPassWord.length() >= 6) {
                    if (RegexUtils.checkPassWord(mPassWord)) {
                        //密码输入格式正确
                        mTvNote.setTextColor(ContextCompat.getColor(mContext, R.color.color_grey_888888));
                    } else {
                        //密码输入格式错误
                        mTvNote.setTextColor(ContextCompat.getColor(mContext, R.color.red));
                    }
                } else {
                    mTvNote.setTextColor(ContextCompat.getColor(mContext,R.color.color_grey_888888));
                }
            }
        });

        mBtnSubmit.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                mPassWord = mEtPassword.getText().toString();
                if (mPassWord.length() >= 6) {
                    if (!TextUtils.isEmpty(mPassWord)) {
                        String time = getTime();
                        String md5Pass = MD5Utils.getMd5Value(mPassWord);
                        getSignUpResult(time, md5Pass);
                    }
                } else {
                    mTvNote.setTextColor(ContextCompat.getColor(SignUpEnterPasswordActivity.this, R.color.red));
                }

            }
        });
    }

    /**
     * 获取当前系统时间的时间戳
     *
     * @return 时间戳
     */
    public String getTime() {
        //获取系统时间的10位的时间戳
        long time = System.currentTimeMillis() / 1000;
        return String.valueOf(time);
    }

    /**
     * 获取注册结果
     *
     * @param time 注册时间
     * @param pass 用户密码
     */
    private void getSignUpResult(String time, String pass) {
        //构建body
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("app", HttpRequestConstant.REQUEST_APP_KEY)
                .addFormDataPart("code", mSafeCode)
                .addFormDataPart("tel", mPhoneNum)
                .addFormDataPart("name", "小率" + time)
                .addFormDataPart("pass", pass)
                .addFormDataPart("addtime", time)
                .build();
        Observable<CodeBean> singUp = DataManager.getSignUpResult(
                requestBody
        );
        Observable<CodeBean> signUpBeanObservable = singUp.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        signUpBeanObservable.subscribe(new DisposableObserver<CodeBean>() {

            @Override
            public void onNext(@NonNull CodeBean signUpBean) {
                int code = signUpBean.getCode();
                switch (code) {
                    case 200:
                        getLoginResult();
                        showShortText("注册成功，正在登录");
                        break;
                    case 403:
                        getLoginResult();
                        showShortText("注册成功，正在登录");
                        break;
                    case 405:
                        showShortText("验证码错误");
                        break;
                        default:break;
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                LogUtils.e(e.getMessage(), "getSignUpResultError");
                showShortText("请求失败");
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 登录请求
     */
    private void getLoginResult() {
        Observable<LoginBean> loginResult = DataManager.getLoginResult(
                mPhoneNum,
                MD5Utils.getMd5Value(mPassWord)
        );
        Observable<LoginBean> signUpBeanObservable = loginResult.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        signUpBeanObservable.subscribe(new DisposableObserver<LoginBean>() {

            @Override
            public void onNext(@NonNull LoginBean bean) {
                int code = bean.getCode();
                switch (code) {
                    case 200:
                        showShortText("登陆成功");
                        LoginBean.DataBean data = bean.getData();
                        SPUtils.put(mContext, "uid", data.getUid());
                        SPUtils.put(mContext, "sex", data.getSex());
                        SPUtils.put(mContext, "photo", data.getPhoto());
                        SPUtils.put(mContext, "tel", data.getTel());
                        SPUtils.put(mContext, "status", data.getStatus());
                        SPUtils.put(mContext, "name", data.getName());
                        SPUtils.put(mContext, "email", data.getEmail());
                        SPUtils.put(mContext, "unit", data.getUnit());
                        JPushInterface.setAlias(mContext, AppConstant.MSG_SET_ALIAS, data.getUid());
                        break;
                    case 401:
                        showShortText("用户不存在");
                        break;
                    case 402:
                        showShortText("密码错误");
                        break;
                    default:
                        showShortText("登陆失败");
                        break;
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                LogUtils.e(e.getMessage(), "getLoginResultError");
                if (retryConnectLogin < 5) {
                    retryConnectLogin++;
                    getLoginResult();
                } else {
                    retryConnectLogin = 0;
                    showShortText("登录请求失败");
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }
}
